package nju.se.alibaba.algorithm;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Inet4Address;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import nju.se.alibaba.dao.AlibabaDAO;
import nju.se.alibaba.model.Tmall;

public class Algorithm_hds_month extends Algorithm{
	HashMap<Integer, HashSet<Integer>> result = new HashMap<Integer, HashSet<Integer>>();
	public void run(){
		doByMonth(105,135,4);
		doByMonth(135,166,5);
		doByMonth(166,196,6);
		doByMonth(196,227,7);
//		int j=1;
//		for(int i=105;i<217;i+=10){
//			doByMonth(i,i+10,j);
//			j++;
//		}
		writeToConsole(result);
		writeToFileInSPMF(result);
	}
	public void doByMonth(int start,int end,int version){
		List<Tmall> list = AlibabaDAO.getBrandIdListByUserIdByMonth(start,end);

		for (int i = 0; i < list.size(); i++) {
			Tmall tmall = list.get(i);
			Integer user_id = tmall.getUser_id();
			Integer brand_id = tmall.getBrand_id();
			user_id = Integer.parseInt(""+version+user_id);
			if (result.containsKey(user_id)) {
				HashSet<Integer> brands = result.get(user_id);
				brands.add(brand_id);
				result.put(user_id, brands);
			} else {
				HashSet<Integer> brands = new HashSet<Integer>();
				brands.add(brand_id);
				result.put(user_id, brands);
			}
		}
	}
	public void writeToFileInSPMF(HashMap<Integer, HashSet<Integer>> result){
		try {
			FileWriter outFile = new FileWriter(new File("spmf_result.txt"));
			Set<Integer>keys = result.keySet();
			for(Integer key:keys){
				//outFile.write(key+"\t");
				HashSet<Integer>brands=result.get(key);
				String tmp = "";
				for (Integer brand:brands) {
					tmp+=brand+" ";
				}
				tmp = tmp.substring(0, tmp.length()-2);
				tmp+="\n";
				outFile.write(tmp);
				outFile.flush();

			}
			outFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
